﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using Model;
using Common;
using MySql.Data.MySqlClient;

namespace DAL
{
    public class SOP_CustomerDAL
    {
        #region 用户注册到SOP上

        /// <summary>
        /// BA推荐注册
        /// </summary>
        /// <param name="Ent"></param>
        /// <param name="Remark"></param>
        /// <param name="IPAddress"></param>
        /// <param name="UserID"></param>
        /// <returns></returns>
        public int AddCustomer_Web(SOP_Customer Ent, String Remark, String IPAddress, out int UserID, out bool IsSync)
        {
            API_CustomerInfoObj CustomerInfo = new API_CustomerInfoObj();
            UserID = 0;
            IsSync = false;
            using (MySqlConnection conn = DAL.SqlHelper.Settings.GetSOPMySqlConnection(true))
            {
                try
                {
                    MySqlCommand cmd = new MySqlCommand("P_AddCustomerByBossID_Web", conn);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add("@BossID_Para", MySqlDbType.VarChar, 20).Value = Ent.BossID;
                    cmd.Parameters.Add("@Mobile_Para", MySqlDbType.VarChar, 11).Value = Ent.Mobile;
                    cmd.Parameters.Add("@UserName_Para", MySqlDbType.VarChar, 32).Value = Ent.UserName;
                    cmd.Parameters.Add("@Password_Para", MySqlDbType.VarChar, 20).Value = Ent.Password;
                    cmd.Parameters.Add("@CardCode_Para", MySqlDbType.VarChar, 20).Value = Ent.CardCode;
                    cmd.Parameters.Add("@CardType_Para", MySqlDbType.VarChar, 20).Value = Ent.CardType;
                    cmd.Parameters.Add("@Who_Para", MySqlDbType.Int32).Value = Ent.Who;
                    cmd.Parameters.Add("@DeviceUUID_Para", MySqlDbType.VarChar, 100).Value = Ent.DeviceUUID;
                    cmd.Parameters.Add("@RecommendID_Para", MySqlDbType.Int32).Value = Ent.RecommendID;
                    cmd.Parameters.Add("@RecommendCode_Para", MySqlDbType.VarChar, 20).Value = Ent.RecommendCode;
                    cmd.Parameters.Add("@RecommendUserName_Para", MySqlDbType.VarChar, 100).Value = Ent.RecommendUserName;
                    cmd.Parameters.Add("@IPAddress_Para", MySqlDbType.VarChar, 20).Value = IPAddress;
                    cmd.Parameters.Add("@Remark_Para", MySqlDbType.VarChar, 100).Value = Remark;
                    cmd.Parameters.Add("@AddTime_Para", MySqlDbType.DateTime).Value = System.DateTime.Now;
                    cmd.Parameters.Add("@IsSuccess_Para", MySqlDbType.Int32).Value = 0;
                    cmd.Parameters.Add("@IsSync_Para", MySqlDbType.Int32).Value = 0;

                    cmd.Parameters["@IsSuccess_Para"].Direction = ParameterDirection.Output;
                    cmd.Parameters["@IsSync_Para"].Direction = ParameterDirection.Output;
                    if (conn.State == ConnectionState.Closed)
                    {
                        conn.Open();
                    }
                    cmd.ExecuteNonQuery();
                    Object IsSuccessObj = cmd.Parameters["@IsSuccess_Para"].Value;
                    Object IsSyncObj = cmd.Parameters["@IsSync_Para"].Value;
                    int isSuccess = IsSuccessObj == null || IsSuccessObj.ToString() == string.Empty ? -5 : (int)IsSuccessObj;
                    int IsSyncInt = IsSyncObj == null || IsSyncObj.ToString() == string.Empty ? -5 : (int)IsSyncObj;
                    UserID = isSuccess;
                    IsSync = IsSyncInt > 0 ? true : false;
                }
                catch (Exception ex)
                {
                    return -1000;
                }
                finally
                {
                    conn.Close();
                }
            }
            return UserID;
        }

        #endregion

        #region 获取个人信息
        /// <summary>
        /// 获取个人信息
        /// </summary>
        /// <param name="CustomerID"></param>
        /// <returns></returns>
        public API_CustomerInfoObj GetCustomerInfoByCustomerID(int CustomerID)
        {

            API_CustomerInfoObj CustomerInfo = new API_CustomerInfoObj();

            //string CacheKey = "ARCSOFTCRAPICustomerInfo$" + CustomerID.ToString();
            //try
            //{
            //    CustomerInfo = Common.MemCachedHelper.GetCache(CacheKey) as API_CustomerInfoObj;
            //    if (CustomerInfo != null)
            //        return CustomerInfo;
            //}
            //catch { }
            using (MySqlConnection conn = DAL.SqlHelper.Settings.GetSOPMySqlConnection(false))
            {
                try
                {
                    StringBuilder strSql = new StringBuilder();
                    strSql.Append("select a.CustomerID,UserName,Sex,Age,Skin,PhotoUrl,Mobile,Birthday,BirthType,Province,City,District,Street,Dollar,MemberID,Job,PerfectUserInfo ");
                    strSql.Append("from SOP_Customers a,SOP_CustomerCard b where a.CustomerID=@CustomerID_Para and a.CustomerID=b.CustomerID and b.Status=5 and b.IsRegisterAmp=5 limit 1; ");
                    MySqlCommand cmd = new MySqlCommand(strSql.ToString(), conn);
                    cmd.CommandType = CommandType.Text;
                    cmd.Parameters.Add("@CustomerID_Para", MySqlDbType.Int32).Value = CustomerID;

                    if (conn.State == ConnectionState.Closed)
                    {
                        conn.Open();
                    }
                    MySqlDataReader sdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                    if (sdr != null)
                    {
                        CustomerInfo = new API_CustomerInfoObj();
                        while (sdr.Read())
                        {

                            CustomerInfo.CustomerID = Convert.ToInt32(sdr["CustomerID"].ToString());
                            CustomerInfo.PhotoUrl = sdr["PhotoUrl"].ToString();
                            CustomerInfo.Sex = sdr["Sex"].ToString();
                            CustomerInfo.Age = sdr["Age"].ToString();
                            CustomerInfo.UserName = sdr["UserName"].ToString();
                            CustomerInfo.Mobile = sdr["Mobile"].ToString();
                            if (!string.IsNullOrWhiteSpace(sdr["Birthday"].ToString()))
                                CustomerInfo.Birthday = Convert.ToDateTime(sdr["Birthday"].ToString()).ToString("yyyy-MM-dd");
                            if (!string.IsNullOrWhiteSpace(sdr["BirthType"].ToString()))
                                CustomerInfo.BirthType = Convert.ToInt32(sdr["BirthType"].ToString());
                            CustomerInfo.Skin = sdr["Skin"].ToString();
                            CustomerInfo.Province = sdr["Province"].ToString();
                            CustomerInfo.City = sdr["City"].ToString();
                            CustomerInfo.District = sdr["District"].ToString();
                            CustomerInfo.Street = sdr["Street"].ToString();
                            if (!string.IsNullOrWhiteSpace(sdr["Dollar"].ToString()))
                                CustomerInfo.Dollar = Convert.ToInt32(sdr["Dollar"].ToString());
                            else
                                CustomerInfo.Dollar = 0;
                            CustomerInfo.MemberID = sdr["MemberID"].ToString();
                            if (!string.IsNullOrWhiteSpace(sdr["Job"].ToString()))
                                CustomerInfo.Job = sdr["Job"].ToString();
                            else
                                CustomerInfo.Job = "0";
                            CustomerInfo.PerfectUserInfo = sdr["PerfectUserInfo"].ToString();
                        }
                    }

                    //if (!string.IsNullOrEmpty(CustomerInfo.CustomerID.ToString()))
                    //    Common.MemCachedHelper.AddCache(CacheKey, CustomerInfo, TimeSpan.FromMinutes(30));
                    //else
                    //    CustomerInfo = null;
                }
                catch (Exception ex)
                {
                    // return -5;
                }
                finally
                {
                    conn.Close();
                }
                return CustomerInfo;
            }
        }


        /// <summary>
        /// 获取个人信息
        /// </summary>
        /// <param name="CustomerID"></param>
        /// <returns></returns>
        public API_CustomerInfoObj GetCustomerInfoAndMemberIDByCustomerID(int CustomerID, string BossID)
        {

            API_CustomerInfoObj CustomerInfo = new API_CustomerInfoObj();

            string CacheKey = "ARCSOFTCRAPICustomerMemberID$" + CustomerID.ToString();
            try
            {
                CustomerInfo = Common.MemCachedHelper.GetCache(CacheKey) as API_CustomerInfoObj;
                if (CustomerInfo != null)
                    return CustomerInfo;
            }
            catch { }
            using (MySqlConnection conn = DAL.SqlHelper.Settings.GetSOPMySqlConnection(false))
            {
                try
                {
                    StringBuilder strSql = new StringBuilder();
                    strSql.Append("select a.CustomerID,UserName,Sex,Age,Skin,PhotoUrl,Mobile,Birthday,BirthType,Province,City,District,Street,(select MemberID from SOP_CustomerCard where CustomerID=a.CustomerID and BossID=b.BossID and Status=5 and IsRegisterAmp=5 and ifnull(MemberID,0)>0 order by CardID desc limit 1) as MemberID ");
                    strSql.Append("from SOP_Customers a,SOP_CustomerCard b where a.CustomerID=@CustomerID_Para and a.CustomerID=b.CustomerID and b.BossID=@BossID_Para and b.Status=5 and b.IsRegisterAmp=5 order by b.CardID desc limit 1; ");
                    MySqlCommand cmd = new MySqlCommand(strSql.ToString(), conn);
                    cmd.CommandType = CommandType.Text;
                    cmd.Parameters.Add("@CustomerID_Para", MySqlDbType.Int32).Value = CustomerID;
                    cmd.Parameters.Add("@BossID_Para", MySqlDbType.VarChar, 20).Value = BossID;

                    if (conn.State == ConnectionState.Closed)
                    {
                        conn.Open();
                    }
                    MySqlDataReader sdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                    if (sdr != null)
                    {
                        CustomerInfo = new API_CustomerInfoObj();
                        while (sdr.Read())
                        {

                            CustomerInfo.CustomerID = Convert.ToInt32(sdr["CustomerID"].ToString());
                            CustomerInfo.PhotoUrl = sdr["PhotoUrl"].ToString();
                            CustomerInfo.Sex = sdr["Sex"].ToString();
                            CustomerInfo.Age = sdr["Age"].ToString();
                            CustomerInfo.UserName = sdr["UserName"].ToString();
                            CustomerInfo.Mobile = sdr["Mobile"].ToString();
                            if (!string.IsNullOrWhiteSpace(sdr["Birthday"].ToString()))
                                CustomerInfo.Birthday = Convert.ToDateTime(sdr["Birthday"].ToString()).ToString("yyyy-MM-dd");
                            if (!string.IsNullOrWhiteSpace(sdr["BirthType"].ToString()))
                                CustomerInfo.BirthType = Convert.ToInt32(sdr["BirthType"].ToString());
                            CustomerInfo.Skin = sdr["Skin"].ToString();
                            CustomerInfo.Province = sdr["Province"].ToString();
                            CustomerInfo.City = sdr["City"].ToString();
                            CustomerInfo.District = sdr["District"].ToString();
                            CustomerInfo.Street = sdr["Street"].ToString();
                            CustomerInfo.MemberID = sdr["MemberID"].ToString();
                        }
                    }

                    if (!string.IsNullOrEmpty(CustomerInfo.CustomerID.ToString()))
                        Common.MemCachedHelper.AddCache(CacheKey, CustomerInfo, TimeSpan.FromMinutes(30));
                    else
                        CustomerInfo = null;
                }
                catch (Exception ex)
                {
                    // return -5;
                }
                finally
                {
                    conn.Close();
                }
                return CustomerInfo;
            }
        }

        /// <summary>
        /// 通过CustomerID获取用户信息
        /// </summary>
        /// <param name="CustomerID"></param>
        /// <returns></returns>
        public SOP_Customer GetSingleCustomerByCustomerID(int CustomerID)
        {
            SOP_Customer model = new SOP_Customer();
            using (MySqlConnection conn = DAL.SqlHelper.Settings.GetSOPMySqlConnection(false))
            {
                try
                {
                    StringBuilder strSql = new StringBuilder();
                    strSql.Append("select * from SOP_Customers where CustomerID=@CustomerID_Para ");
                    MySqlCommand cmd = new MySqlCommand(strSql.ToString(), conn);
                    cmd.CommandType = CommandType.Text;
                    cmd.Parameters.Add("@CustomerID_Para", MySqlDbType.Int32).Value = CustomerID;

                    if (conn.State == ConnectionState.Closed)
                    {
                        conn.Open();
                    }
                    MySqlDataReader sdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                    if (sdr != null)
                    {
                        while (sdr.Read())
                        {
                            if (!string.IsNullOrWhiteSpace(sdr["CustomerID"].ToString()))
                                model.CustomerID = Convert.ToInt32(sdr["CustomerID"].ToString());

                            model.Mobile = sdr["Mobile"].ToString();
                            if (!string.IsNullOrWhiteSpace(sdr["Sex"].ToString()))
                                model.Sex = Convert.ToInt32(sdr["Sex"].ToString());
                            model.Age = sdr["Age"].ToString();
                            model.PhotoUrl = sdr["PhotoUrl"].ToString();
                            model.Skin = sdr["Skin"].ToString();
                            if (!string.IsNullOrWhiteSpace(sdr["Birthday"].ToString()))
                                model.Birthday = Convert.ToDateTime(sdr["Birthday"].ToString());
                            if (!string.IsNullOrWhiteSpace(sdr["BirthType"].ToString()))
                                model.BirthType = Convert.ToInt32(sdr["BirthType"].ToString());

                            model.UserName = sdr["UserName"].ToString();

                            model.Province = sdr["Province"].ToString();
                            model.City = sdr["City"].ToString();
                        }
                    }
                }
                catch (Exception ex)
                {
                    return null;
                }
                finally
                {
                    conn.Close();
                }
            }
            return model;
        }
        #endregion

        #region 更新用户地址
        /// <summary>
        /// 更新用户地址
        /// </summary>
        /// <param name="model"></param>
        /// <param name="error"></param>
        /// <returns></returns>
        public int UpdateAddressByCustomerID(SOP_Customer model, out String error)
        {
            error = "";
            using (MySqlConnection conn = DAL.SqlHelper.Settings.GetSOPMySqlConnection(true))
            {
                try
                {
                    MySqlCommand cmd = new MySqlCommand("P_SetCustomerAddressByCustomerID_API", conn);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add("@CustomerID_Para", MySqlDbType.Int32).Value = model.CustomerID;
                    cmd.Parameters.Add("@Province_Para", MySqlDbType.VarChar, 30).Value = model.Province;
                    cmd.Parameters.Add("@City_Para", MySqlDbType.VarChar, 30).Value = model.City;
                    cmd.Parameters.Add("@District_Para", MySqlDbType.VarChar, 100).Value = model.District;
                    cmd.Parameters.Add("@Street_Para", MySqlDbType.VarChar, 100).Value = model.Street;
                    cmd.Parameters.Add("@IsSuccess_Para", MySqlDbType.Int32).Value = 0;
                    cmd.Parameters["@IsSuccess_Para"].Direction = ParameterDirection.Output;
                    if (conn.State == ConnectionState.Closed)
                    {
                        conn.Open();
                    }
                    cmd.ExecuteNonQuery();
                    Object IsSuccessObj = cmd.Parameters["@IsSuccess_Para"].Value;
                    int isSuccess = IsSuccessObj == null || IsSuccessObj.ToString() == string.Empty ? -5 : (int)IsSuccessObj;

                    return isSuccess;

                }
                catch (Exception ex)
                {
                    error = ex.Message.ToString();
                    return -1000;
                }
                finally
                {
                    conn.Close();
                }
            }
        }
        #endregion

    }
}
